<?php

namespace common\models\business;

use common\models\sys\SysSetting;
use Yii;
use common\models\business\BusinessVariety;
use yii\db\Expression;
use yii\db\Query;

/**
 * This is the model class for table "business_pig".
 *
 * @property integer $id
 * @property string $no
 * @property string $weight
 * @property string $height
 * @property integer $varietyid
 * @property string $batch
 * @property integer $beforevaccinetime
 * @property integer $aftervaccinetime
 * @property integer $intime
 * @property integer $planout
 * @property integer $livery
 * @property integer $status
 * @property string $gender
 * @property string $father
 * @property string $mathor
 * @property integer $fileid
 * @property string $photo
 * @property string $screen_photo
 */
class BusinessPig extends \yii\db\ActiveRecord
{


    //主要用于日志记录
    public $uselog = [
        'tabcomment' => '仔猪',      //用于修改了什么的显示
        'mainfield' => 'no',      //主要的显示标题的字段
        'picturefield' => ['photo','screen_photo'],        //图片字段
        'timefield' => ['beforevaccinetime','aftervaccinetime','intime','planout'],       //时间字段
        'unsetfiled' =>[],      //不需要记录的字段
    ];

    const STATUS_BRFOREIN = 1;
    const STATUS_AFTERIN = 2;
    const STATUS_WAITOUT = 3;
    const STATUS_WAITKILL = 4;
    const STATUS_KILLED = 5;
    const STATUS_DIEED = 6;
    const STATUS_EXCEPTION = 7;



    public static $statues = [
        self::STATUS_BRFOREIN => '未入栏',
        self::STATUS_AFTERIN => '已入栏',
        self::STATUS_WAITOUT => '出栏',
        self::STATUS_WAITKILL => '待宰杀',
        self::STATUS_KILLED => '已宰杀',
        self::STATUS_DIEED => '死亡',
        self::STATUS_EXCEPTION => '异常',
    ];


    //健康状态
    public static $healthy_status = [
        '良好','正常','一般','差'
    ];

    //猪舍环境
    public static $pigpen_status = [
        '良好','正常','一般','差'
    ];

    //体测数据
    public static $body_status = [
        '良好','正常','一般','差'
    ];


    /**
     * @var array
     * 预出栏原因
     */
    public static $outreason = [
        '出栏预警','体征达标'
    ];


    /**
     * @var array
     * 异常原因
     */
    public static $exceptionreason = [
        '仔猪死亡','农户不养','农户条件不足','农户搬家'
    ];

    /**
     * @var array
     * 宰杀方式
     */
    public static $killtype = [
        ['name' => '土法宰杀','price' =>200, 'desc' => '通过突发宰杀的猪具有完整性，定制性等优点，可以依照用户需求，选择最佳的割肉方式，同时，猪肉的品质也会被保证到最好，具有独特的乡村风味。'],
        ['name' => '屠宰场宰杀','price' => 120,'desc' => '通过突发宰杀的猪具有完整性，定制性等优点，可以依照用户需求，选择最佳的割肉方式，同时，猪肉的品质也会被保证到最好，具有独特的乡村风味。']
    ];


    const CANLIVERY = 1;
    const NOTCANLIVERY = 0;
    public static $canlivery = [
        self::CANLIVERY => '可以领养',
        self::NOTCANLIVERY => '不可以领养'
    ];

    const INDEX_SHOW = 1;
    const INDEX_hIDDEN = 0;
    public static $isindex = [
        self::INDEX_SHOW => '首页显示',
        self::INDEX_hIDDEN => '首页不显示'
    ];





    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'business_pig';
    }



    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['no', 'varietyid','batch', 'planout', 'status','fileid'], 'required'],
            [['varietyid', 'livery', 'status', 'fileid','headpersonid','isindex','canlivery','contract_purid'], 'integer'],
            [['no', 'gender','father', 'mathor','unino','headperson','liveryremark','activelevel','haircolor','foodintake','shit','breath','video'], 'string', 'max' => 255],
            [['batch'], 'string', 'max' => 11],
            [['weight','height', 'length','width','price','temperature','cost','ling_total_price'], 'number'],
            [['weight','height', 'length','width','price','cost','ling_total_price'],  'default', 'value' => 0],
            [['livery','headpersonid'], 'default', 'value' => 0],
            [['photo','screen_photo'], 'image', 'extensions' => 'jpg, jpeg, gif, png','on' => ['insert', 'update'], 'maxFiles' => 15],
            [['video'], 'file', 'extensions' => 'mp4','on' => ['insert', 'update']],
            [['no','unino'],'unique'],
            ['unino','default','value'=>''],
            [['beforevaccinetime','aftervaccinetime','intime','planout'], 'safe'],
            [['slaughter'],'string']
        ];
    }




    public function scenarios()
    {
        $scenarios = parent::scenarios();//本行必填，不写的话就会报如上错误
        $scenarios['create'] = ['photo', 'screen_photo,video'];
        $scenarios['update'] = ['photo', 'screen_photo,video'];

        return $scenarios;
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'no' => '仔猪编号',
            'unino' => '国家畜牧统一编码',
            'weight' => '体重(kg)',
            'height' => '高度(cm)',
            'length' => '体长(cm)',
            'width' => '体宽(cm)',
            'situation' => '体测状态',
            'variety' => '品种',
            'varietyid' => '品种',
            'batch' => '批次',
            'beforevaccinetime' => '入栏前疫苗时间',
            'aftervaccinetime' => '入栏后疫苗时间',
            'intime' => '入栏时间',
            'planout' => '预计出栏时间',
            'livery' => '代养农户',
            'status' => '状态',
            'gender' => '性别',
            'father' => '父本',
            'mathor' => '母本',
            'fileid' => '档案号',
            'photo' => '照片',
            'activelevel' => '精神状态',
            'haircolor' => '毛色',
            'foodintake' => '饮食',
            'shit' => '大便情况',
            'breath' => '呼吸情况',
            'temperature' => '体温',
            'liveryremark' => '代养人备注',
            'headpersonid' => '负责人',
            'lingperson' => '领养人',
            'canlivery' => '是否可以领养',
            'isindex' => '是否认养首页显示',
            'screen_photo' => '大屏幕用图',
            'newno' => '自定义编码',
            'price' => '领养定金',
            'ling_total_price' => '领养总价格',
            'contract_purid' => '购进单',
            'cost' => '猪仔成本',
            'video' => '仔猪视频',
            'slaughter' => '屠宰后的流程'
        ];
    }


    /**
     * @param $status
     * @return string
     * 状态转换为颜色
     */
    public static function status2color($status)
    {
        if($status == '未入栏'){
            return '#ccc';
        }else if($status == '已入栏'){
            return '#41cac0';
        }else if($status == '出栏'){
            return '#008e83';
        }else if($status == '待宰杀'){
            return '#dc8a83';
        }else if($status == '已宰杀'){
            return '#237780';
        }else if($status == '死亡'){
            return '#909193';
        }else if($status == '异常'){
            return '#a94442';
        }
    }


    public function beforeSave($insert)
    {
        $this->beforevaccinetime = strtotime($this->beforevaccinetime);
        $this->aftervaccinetime = strtotime($this->aftervaccinetime);
        $this->intime = strtotime($this->intime);
        $this->planout = strtotime($this->planout);
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取猪种
     */
    public function getVariety()
    {
        return $this->hasOne(BusinessVariety::className(),['id'=>'varietyid']);
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取猪档案
     */
    public function getFile()
    {
        return $this->hasOne(BusinessPigFile::className(),['id'=>'fileid']);
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取认养农户
     */
    public function getLiveryperson()
    {
        return $this->hasOne(BusinessFarmers::className(),['id'=>'livery']);
    }


    /**
     * @return \yii\db\ActiveQuery
     * 获取负责人
     */
    public function getPerson()
    {
        return $this->hasOne(BusinessPerson::className(),['id'=>'headpersonid']);
    }

    /**
     * @return \yii\db\ActiveQuery
     * 获取领养人
     */
    public function getLinger()
    {
        return $this->hasOne(BusinessUser::className(),['id'=>'lingperson']);

    }


    /**
     * 获取巡检记录
     */
    public function getInspection()
    {
        return $this->hasMany(BusinessInspection::className(),['pigid'=>'id']);
    }



    //检测仔猪巡检
    public function getIsinspection()
    {
        //现在距离一个巡检周期的时间点
        return self::isInspection($this->id);
    }


    public function getNewisinspection()
    {
        //现在距离一个巡检周期的时间点
        return self::newIsInspection($this->id);
    }


    /**
     * @param $pigid
     * @return array|bool
     * 判断是否巡检（判断方法，这个猪仔的最近一次巡检距离现在是否超过一个巡检周期）
     */
    public static function isInspection($pigid)
    {
        //现在距离一个巡检周期的时间点
        $difftime = time()-(SysSetting::getValue('inspection_cycle')*24*3600);

        return (new Query())->select('id,status as insstatus')
            ->from(BusinessInspection::tableName())
            ->where('pigid=:id and createtime>:dtime and is_del!=:del',[':id'=>$pigid,':dtime'=>$difftime,':del'=>BusinessInspection::ISDEL_DEL])
            ->orderBy('id desc')
            ->one();
    }


    /**
     *
     * 仔猪成本
     */
    public function getPigcost()
    {
        return $this->hasMany(BusinessCost::className(),['pigid'=>'id']);
    }

    /**
     * @param $pigid
     * @return array|bool
     * 判断是否该巡检了
     */
    public static function newIsInspection($pigid)
    {
        //现在距离一个巡检周期的时间点
        $difftime = time()-(SysSetting::getValue('inspection_cycle')*24*3600);

        return (new Query())->select('id,status as insstatus,remark')
            ->from(NewBusinessInspection::tableName())
            ->where('pigid=:id and createtime>:dtime and is_del!=:del',[':id'=>$pigid,':dtime'=>$difftime,':del'=>NewBusinessInspection::ISDEL_DEL])
            ->orderBy('id desc')
            ->one();
    }


    /**
     * @return $this
     *
     */
    public function getDailyCost()
    {
        //取出日常成本
        $sum = new Expression('sum(cost.price) as total');
        $model = BusinessCost::find()->select($sum)->alias('cost')
            ->leftJoin(BusinessPig::tableName().' as pig','pig.id=cost.pigid')
            ->where('pig.id=:id and cost.status=:status',[':id'=>$this->id,':status'=>BusinessCost::STATUS_CONFIRM])
            ->scalar();
        return $model?$model:0;
    }



    /**
     * @return $this
     * 获取回购价格
     */
    public function getBack()
    {
        $model = BusinessBackpig::find()->select('backprice')
            ->where('pigid=:id',[':id'=>$this->id]);
        return $model;
    }


    /**
     * @return $this
     * 获取分割成本
     */
    public function getFg()
    {
        $model = BusinessPigPrice::find()->select('fgcost')
            ->where('pigid=:id',[':id'=>$this->id]);
        return $model;
    }


    public function getTotal()
    {
        $fgost = $this->fg?$this->fg->fgcost:0;
        $backcost  = $this->back?$this->back->backprice:0;
        $cost = $this->getDailyCost();

        return $total = $fgost+$backcost+$cost+$this->cost;
    }


    /**
     *
     * 获取仔猪疫苗情况
     */
    public function getVaccine()
    {
        return $this->hasMany(BusinessVaccine::className(),['pigid'=>'id']);

    }






}
